﻿using Dapper;
using System;
using BCEntity.Sim.StaffNotification;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Sim.StaffNotification
{
    /// <summary>
    /// 员工通知信息
    /// </summary>
	public class StaffNotificationData : IStaffNotificationData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM staffnotification";
        private const string QUERY = @"SELECT StaffNotificationId,Content,AdminId,CreateTime,IsRead,ReadTime FROM staffnotification";
        public StaffNotificationData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查员工通知信息是否存在
        public async Task<bool> Exists(long staffNotificationId)
        {
            string sql = string.Format(@"{0} WHERE StaffNotificationId=?StaffNotificationId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?StaffNotificationId", staffNotificationId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加员工通知信息
        public async Task<StaffNotificationEntity> Add(StaffNotificationEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("staffnotification", new string[] { "Content", "AdminId", "IsRead", });
            sql = string.Format("{0} {1} WHERE StaffNotificationId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Content", entity.Content?.Trim(), DbType.String);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
            parameters.Add("?IsRead", entity.IsRead, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<StaffNotificationEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改员工通知信息
        public async Task<StaffNotificationEntity> Update(StaffNotificationEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("staffnotification", new string[] { "IsRead", "ReadTime" }, new string[] { "StaffNotificationId" });
            sql = string.Format("{0} {1} WHERE StaffNotificationId=?StaffNotificationId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?StaffNotificationId", entity.StaffNotificationId, DbType.Int64, size: 20);
            parameters.Add("?IsRead", true, DbType.Boolean);
            parameters.Add("?ReadTime", entity.ReadTime, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<StaffNotificationEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除员工通知信息
        public async Task<bool> Delete(long staffNotificationId)
        {
            string sql = @"DELETE FROM staffnotification WHERE StaffNotificationId=?StaffNotificationId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?StaffNotificationId", staffNotificationId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取员工通知信息
        public async Task<StaffNotificationEntity> GetEntity(long staffNotificationId)
        {
            string sql = string.Format(@"{0} WHERE StaffNotificationId=?StaffNotificationId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?StaffNotificationId", staffNotificationId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<StaffNotificationEntity>(sql, parameters);
        }
        #endregion

        #region 获取员工通知信息分页
        public async Task<(IEnumerable<StaffNotificationEntity>, int)> Query(long adminId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("AdminId=?AdminId");
            parameters.Add("?AdminId", adminId, DbType.Int64);

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM staffnotification {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<StaffNotificationEntity, int>(sql, parameters);
        }
        #endregion

        #region 获取接收人未读消息数量
        public async Task<int> GetNoneReadCount(long adminId)
        {
            string sql = string.Format(@"{0} WHERE AdminId=?AdminId AND IsRead=0", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminId", adminId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync<int>(sql, parameters);
        }
        #endregion
    }
}
